package org.chs.ts.batch.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @Compay 盛唐天行
 * @Author: wuwei
 * @Censor By wuwei
 * @Sence 2024/4/8 10:01
 * @Modify 2024/4/8 10:01
 * @Description
 */
@Component
@Slf4j
public class RedisBuilder {
    @Resource
    RedisTemplate redisTemplate;


    public void sleepThread()
    {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    public boolean checkUpdateRedisLock(String key) {
        if (Boolean.FALSE.equals(getUpdateRedisLock(key))) {
            log.info("---------------------------- 获取到取更新数据库 redis锁----------------------------");
            insUpdateRedisLock(key);
            return true;
        }
        return false;
    }

    /**
     * 获取更新数据库 redis锁
     */
    private boolean getUpdateRedisLock(String key) {
        return redisTemplate.hasKey(key);
    }

    /**
     * 插入更新数据库 redis锁
     */
    private void insUpdateRedisLock(String lockKey) {
        insRedis(lockKey, System.currentTimeMillis(), 1, TimeUnit.MINUTES);
    }

    /**
     * 删除更新数据库 redis锁
     *
     * @param key redis-key
     * @return 删除结果
     */
    public boolean unUpdateRedisLock(String key) {
        return unRedisLock(key);
    }

    private boolean unRedisLock(String key) {
        final boolean result = Boolean.TRUE.equals(redisTemplate.delete(key));
        log.info("[redisTemplate redis]释放锁缓存{} key:{}", result ? "成功" : "失败", key);
        return result;
    }



    private void insRedis(String key, Object value, int timeout, TimeUnit timeUnit) {
        redisTemplate.opsForValue().set(key, value, timeout, timeUnit);
    }

}
